// ===== 相册功能 =====

class PhotoGallery {
    constructor() {
        this.uploadArea = document.getElementById('uploadArea');
        this.photoInput = document.getElementById('photoInput');
        this.galleryGrid = document.getElementById('galleryGrid');
        this.photos = [];

        this.init();
    }

    init() {
        if (!this.uploadArea || !this.photoInput || !this.galleryGrid) {
            console.warn('相册元素未找到');
            return;
        }

        this.bindEvents();
        this.loadStoredPhotos();
    }

    bindEvents() {
        // 点击上传区域
        this.uploadArea.addEventListener('click', () => {
            this.photoInput.click();
        });

        // 文件选择
        this.photoInput.addEventListener('change', (e) => {
            this.handleFileSelect(e);
        });

        // 拖拽上传
        this.uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            this.uploadArea.classList.add('drag-over');
        });

        this.uploadArea.addEventListener('dragleave', () => {
            this.uploadArea.classList.remove('drag-over');
        });

        this.uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            this.uploadArea.classList.remove('drag-over');
            this.handleFileDrop(e);
        });
    }

    handleFileSelect(e) {
        const files = Array.from(e.target.files);
        this.processFiles(files);
    }

    handleFileDrop(e) {
        const files = Array.from(e.dataTransfer.files);
        this.processFiles(files);
    }

    processFiles(files) {
        const imageFiles = files.filter(file => file.type.startsWith('image/'));

        imageFiles.forEach(file => {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.addPhoto(e.target.result, file.name);
            };
            reader.readAsDataURL(file);
        });
    }

    addPhoto(src, name) {
        const photo = {
            id: Date.now() + Math.random(),
            src: src,
            name: name,
            timestamp: new Date().toISOString()
        };

        this.photos.push(photo);
        this.renderPhoto(photo);
        this.saveToLocalStorage();
        this.removePlaceholder();
    }

    renderPhoto(photo) {
        const photoElement = document.createElement('div');
        photoElement.className = 'photo-item';
        photoElement.dataset.photoId = photo.id;

        photoElement.innerHTML = `
            <div class="photo-container">
                <img src="${photo.src}" alt="${photo.name}" class="photo-image">
                <div class="photo-overlay">
                    <div class="photo-actions">
                        <button class="photo-btn view-btn" title="查看">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                            </svg>
                        </button>
                        <button class="photo-btn delete-btn" title="删除">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                            </svg>
                        </button>
                    </div>
                    <div class="photo-info">
                        <p class="photo-name">${photo.name}</p>
                        <p class="photo-date">${this.formatDate(photo.timestamp)}</p>
                    </div>
                </div>
            </div>
        `;

        // 绑定事件
        const viewBtn = photoElement.querySelector('.view-btn');
        const deleteBtn = photoElement.querySelector('.delete-btn');
        const img = photoElement.querySelector('.photo-image');

        viewBtn.addEventListener('click', () => this.viewPhoto(photo));
        deleteBtn.addEventListener('click', () => this.deletePhoto(photo.id));
        img.addEventListener('click', () => this.viewPhoto(photo));

        // 添加动画效果
        photoElement.style.animation = 'photoEntry 0.5s ease-out';

        this.galleryGrid.appendChild(photoElement);
    }

    viewPhoto(photo) {
        const modal = this.createPhotoModal(photo);
        document.body.appendChild(modal);

        // 动画显示
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);

        // 点击背景关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                this.closePhotoModal(modal);
            }
        });

        // ESC键关闭
        const handleKeydown = (e) => {
            if (e.key === 'Escape') {
                this.closePhotoModal(modal);
                document.removeEventListener('keydown', handleKeydown);
            }
        };
        document.addEventListener('keydown', handleKeydown);
    }

    createPhotoModal(photo) {
        const modal = document.createElement('div');
        modal.className = 'photo-modal';

        modal.innerHTML = `
            <div class="modal-content">
                <button class="modal-close">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                    </svg>
                </button>
                <img src="${photo.src}" alt="${photo.name}" class="modal-image">
                <div class="modal-info">
                    <h3>${photo.name}</h3>
                    <p>${this.formatDate(photo.timestamp)}</p>
                </div>
            </div>
        `;

        const closeBtn = modal.querySelector('.modal-close');
        closeBtn.addEventListener('click', () => this.closePhotoModal(modal));

        return modal;
    }

    closePhotoModal(modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            modal.remove();
        }, 300);
    }

    deletePhoto(photoId) {
        if (!confirm('确定要删除这张照片吗？')) {
            return;
        }

        // 从数组中移除
        this.photos = this.photos.filter(photo => photo.id !== photoId);

        // 从DOM中移除
        const photoElement = document.querySelector(`[data-photo-id="${photoId}"]`);
        if (photoElement) {
            photoElement.style.animation = 'photoExit 0.3s ease-out';
            setTimeout(() => {
                photoElement.remove();
                this.checkEmptyGallery();
            }, 300);
        }

        this.saveToLocalStorage();
    }

    removePlaceholder() {
        const placeholder = this.galleryGrid.querySelector('.photo-placeholder');
        if (placeholder) {
            placeholder.remove();
        }
    }

    checkEmptyGallery() {
        if (this.photos.length === 0 && !this.galleryGrid.querySelector('.photo-placeholder')) {
            const placeholder = document.createElement('div');
            placeholder.className = 'photo-placeholder';
            placeholder.innerHTML = `
                <div class="placeholder-content">
                    <span>📷</span>
                    <p>第一张照片等待添加...</p>
                </div>
            `;
            this.galleryGrid.appendChild(placeholder);
        }
    }

    formatDate(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    saveToLocalStorage() {
        try {
            localStorage.setItem('galleryPhotos', JSON.stringify(this.photos));
        } catch (error) {
            console.warn('无法保存照片到本地存储:', error);
        }
    }

    loadStoredPhotos() {
        try {
            const stored = localStorage.getItem('galleryPhotos');
            if (stored) {
                this.photos = JSON.parse(stored);
                this.photos.forEach(photo => this.renderPhoto(photo));
                this.removePlaceholder();
            }
        } catch (error) {
            console.warn('无法加载存储的照片:', error);
        }
    }
}

// ===== 初始化相册 =====
document.addEventListener('DOMContentLoaded', function() {
    window.photoGallery = new PhotoGallery();
});

// ===== 添加CSS样式 =====
const galleryStyles = `
    <style>
        .photo-item {
            position: relative;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            animation: photoEntry 0.5s ease-out;
        }

        .photo-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 50px rgba(0, 0, 0, 0.2);
        }

        .photo-container {
            position: relative;
            aspect-ratio: 1;
            overflow: hidden;
        }

        .photo-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .photo-item:hover .photo-image {
            transform: scale(1.05);
        }

        .photo-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(to bottom, transparent 0%, rgba(0,0,0,0.7) 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding: 1rem;
        }

        .photo-item:hover .photo-overlay {
            opacity: 1;
        }

        .photo-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
        }

        .photo-btn {
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            color: var(--text-color);
        }

        .photo-btn:hover {
            background: var(--accent-color);
            color: white;
            transform: scale(1.1);
        }

        .photo-btn.delete-btn:hover {
            background: var(--emphasis-color);
        }

        .photo-info {
            color: white;
        }

        .photo-name {
            font-size: 0.9rem;
            font-weight: 500;
            margin-bottom: 0.2rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .photo-date {
            font-size: 0.8rem;
            opacity: 0.8;
        }

        .drag-over {
            background: rgba(255, 215, 0, 0.1) !important;
            border-color: var(--accent-color) !important;
            transform: scale(1.02);
        }

        .photo-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity 0.3s ease;
            padding: 2rem;
        }

        .photo-modal.show {
            opacity: 1;
        }

        .modal-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            background: white;
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }

        .modal-close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 10;
            transition: all 0.3s ease;
            color: var(--text-color);
        }

        .modal-close:hover {
            background: var(--emphasis-color);
            color: white;
            transform: scale(1.1);
        }

        .modal-image {
            max-width: 100%;
            max-height: 70vh;
            object-fit: contain;
        }

        .modal-info {
            padding: 1.5rem;
            text-align: center;
        }

        .modal-info h3 {
            margin-bottom: 0.5rem;
            color: var(--text-color);
        }

        .modal-info p {
            color: var(--secondary-color);
            font-size: 0.9rem;
        }

        @keyframes photoEntry {
            from {
                opacity: 0;
                transform: translateY(20px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        @keyframes photoExit {
            from {
                opacity: 1;
                transform: scale(1);
            }
            to {
                opacity: 0;
                transform: scale(0.8);
            }
        }

        @media (max-width: 768px) {
            .photo-btn {
                width: 35px;
                height: 35px;
            }

            .modal-content {
                margin: 1rem;
                max-width: calc(100% - 2rem);
            }

            .modal-info {
                padding: 1rem;
            }

            .modal-info h3 {
                font-size: 1.1rem;
            }
        }
    </style>
`;

// 将样式添加到页面头部
document.head.insertAdjacentHTML('beforeend', galleryStyles);